package com.idanchuang.support.etcache.pubsub.pulsar;

import com.idanchuang.support.etcache.ConditionalOnEtCacheEnabled;
import com.idanchuang.support.etcache.pubsub.*;
import com.idanchuang.support.etcache.remote.codec.RemoteKeyCodec;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author yjy
 * Created at 2022/3/28 5:08 下午
 */
@Configuration
@ConditionalOnEtCacheEnabled
@ConditionalOnClass(ConnectionFactory.class)
@ConditionalOnProperty(prefix = "idanchuang.component.etcache", name = "eventType", havingValue = "pulsar")
public class PulsarRemoteEventAutoConfiguration {

    @Value("${idanchuang.component.base.env:dev}")
    private String env;
    @Value("${spring.application.name}")
    private String appId;
    @Value("${pulsar.client.serviceUrl:${pulsar.client.service-url}}")
    private String serviceUrl;

    @Bean
    @ConditionalOnMissingBean(RemoteEventSubscriber.class)
    public RemoteEventSubscriber remoteEventSubscriber(RemoteKeyCodec remoteKeyCodec, SubEventQueue subEventQueue) throws Exception {
        PulsarProperties properties = new PulsarProperties();
        properties.setServiceUrl(serviceUrl);
        return new PulsarRemoteEventSubscriber(remoteKeyCodec, subEventQueue, env, appId.toLowerCase(), properties);
    }

    @Bean
    @ConditionalOnMissingBean(RemoteEventPublisher.class)
    public RemoteEventPublisher remoteEventPublisher() throws Exception {
        PulsarProperties properties = new PulsarProperties();
        properties.setServiceUrl(serviceUrl);
        return new PulsarRemoteEventPublisher(env, appId.toLowerCase(), properties);
    }

}
